﻿using System;
using System.Collections;
using System.Collections.Generic;
using LogSystem;
using Pathfinding;
using Pathfinding.RVO;
using UnityEngine;
using UnityEngine.Serialization;
using RootMotion.Dynamics;

namespace Yoozoo.Gameplay.Liberty.AI
{
    public class NpcTrigger : MonoBehaviour
    {
        private AIEntity _aiEntity;
        private AIData _aiData;
        
        public float bargeMinSpeed = 2;
        public float deadSpeed = 5;

        public Action<Collider> onTriggerEnterAction;
        public Action<Collider> onTriggerExitAction;
        public void InitData(AIEntity aiEntity)
        {
            _aiEntity = aiEntity;
            _aiData = aiEntity.data;
        }

        private void OnTriggerExit(Collider other)
        {
            if (_aiEntity == null || _aiEntity.puppetMaster == null)
            {
                return;
            }
            onTriggerExitAction?.Invoke(other);
            
            if (_aiData.uniqueId == LibertyAIUtils.PLAYER_AI_ID)
            {
                return;
            }
        }

        void OnTriggerEnter(Collider collider)
        {
            if (_aiEntity == null || !_aiEntity.data.isAlive)
            {
                return;
            }
            onTriggerEnterAction?.Invoke(collider);

            if (collider.CompareTag("LibertyProp"))
            {
                // 道具
                PropItem propItem = collider.GetComponent<PropItem>();
                if (propItem && !propItem.HasBeenTaken)
                {
                    propItem.OnTake(_aiEntity, gameObject);
                }
            }
            else
            {
                // 撞车
                if (_aiEntity.puppetMaster == null)
                {
                    return;
                }
                CarEntity carEntity = LibertyAIUtils.AIManager.CarBirthManager.GetCarEntity(collider);
                if (carEntity != null)
                {
                    float carSpeed = carEntity.carController.getForwardVelocity();
                    if (_aiEntity.data.isAlive &&
                        !_aiEntity.onHitCollider.CompareTag("Protected") &&
                        carSpeed > bargeMinSpeed && 
                        _aiData.npcStatus != NpcStatus.VehicleBarge)
                    {
                        StopAllCoroutines();
                        StartCoroutine(VehicleBarge(carEntity));
                    }
                }
            }
            
        }
        
        [Range(0,4)]
        public float deadDelayTime = 2f;
        private IEnumerator VehicleBarge(CarEntity carEntity)
        {
            // _aiEntity.viewer.animationAgent.EnterBattleState(BattleState.None);
            _aiEntity.viewer.animationAgent.EnterAimingState(AimingState.None);
            _aiEntity.viewer.animationAgent.SetDisableOperate(true);

            NpcStatus lastNpcStatus = _aiData.npcStatus;
            _aiData.npcStatus = NpcStatus.VehicleBarge;
            
            Vector3 carPos = carEntity.position;
            Vector3 carDir = carEntity.forward;
            Vector3 carRight = carEntity.right;
            
            float angle = Vector3.Angle(carDir, transform.position - carPos);
            float v = Vector3.Cross(carDir, transform.position - carPos).y;

            Animator animator = _aiEntity.viewer.animator;
            LocomotionAgent locomotionAgent = _aiEntity.viewer.locomotionAgent;
            locomotionAgent.vehicleBargeTime = 0;
            // 关掉寻路逻辑与行为树

            _aiEntity.characterController.enabled = false;
            _aiEntity.onHitCollider.enabled = false;
            _aiEntity.headCollider.enabled = false;
            
            if (angle < 25)
            {
                Vector3 bargeDir = transform.forward;
                if (v > 0)
                {
                    //右边
                    bargeDir = -(carDir + carRight).normalized;
                }
                else
                {
                    //左边
                    bargeDir = -(carDir - carRight).normalized;
                }

                float angle2 = Vector3.Angle(carDir, animator.transform.forward);
                if (angle2 > 90)
                {
                    animator.CrossFade("vehicle_dead",0.05f,0);
                }
                else
                {
                    animator.CrossFade("vehicle_dead2",0.05f,0);
                }
                 
                locomotionAgent.isVehicleBarge = true;
                locomotionAgent.bargeDir = bargeDir;
                
                yield return new WaitForSeconds(deadDelayTime);
                _aiEntity.puppetMaster.state = PuppetMaster.State.Dead;
                _aiEntity.puppetMaster.enabled = true;
                locomotionAgent.isVehicleBarge = false;
                yield return new WaitForSeconds(4);
            }
            else if(angle < 135)
            {
                animator.CrossFade("vehicle_scratch",0.05f,0);
                locomotionAgent.isVehicleScratch = true;
                locomotionAgent.bargeDir = (transform.position - carPos).normalized;
                
                yield return new WaitForSeconds(1.5f);
                locomotionAgent.isVehicleScratch = false;
                yield return new WaitForSeconds(1.2f);
            }
            
            _aiEntity.characterController.enabled = true;
            _aiEntity.onHitCollider.enabled = true;
            _aiEntity.headCollider.enabled = true;
            _aiData.npcStatus = lastNpcStatus;    // 还原到撞车之前的状态
            _aiEntity.viewer.animationAgent.SetDisableOperate(false);

        }
        
        public void OnNpcDeath()
        {
            Debug.Log("OnNpcDeath");
            if (_aiData.isAlive)
            {
                _aiEntity.puppetMaster.state = PuppetMaster.State.Alive;
            }
        }
        
    }
}